from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, UploadFile, File, Form
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_user
from app.models.user import User
from app.models.image_task import ImageTask
from app.schemas.image_task import (
    ImageTaskCreate, ImageTaskUpdate, ImageTaskResponse, ImageTaskListResponse,
    BatchImageUploadRequest, BatchImageUploadResponse
)
from app.crud.image_task import image_task
from app.services.tencent.cos_service import TencentCOSService
from app.services.image.processor import ImageProcessor
import uuid

router = APIRouter()

@router.post("/tasks", response_model=ImageTaskResponse)
def create_image_task(
    *,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    task_data: ImageTaskCreate
):
    """创建图片任务"""
    return image_task.create_task(db=db, task_data=task_data, user_id=current_user.id)

@router.get("/tasks", response_model=List[ImageTaskListResponse])
def get_user_image_tasks(
    *,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    skip: int = 0,
    limit: int = 100
):
    """获取用户的图片任务列表"""
    return image_task.get_user_tasks(db=db, user_id=current_user.id, skip=skip, limit=limit)

@router.get("/tasks/{task_id}", response_model=ImageTaskResponse)
def get_image_task(
    *,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    task_id: int
):
    """获取图片任务详情"""
    task = image_task.get_task(db=db, task_id=task_id, user_id=current_user.id)
    if not task:
        raise HTTPException(status_code=404, detail="任务不存在")
    return task

@router.put("/tasks/{task_id}", response_model=ImageTaskResponse)
def update_image_task(
    *,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    task_id: int,
    task_data: ImageTaskUpdate
):
    """更新图片任务"""
    task = image_task.update_task(db=db, task_id=task_id, user_id=current_user.id, task_data=task_data)
    if not task:
        raise HTTPException(status_code=404, detail="任务不存在")
    return task

@router.delete("/tasks/{task_id}")
def delete_image_task(
    *,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    task_id: int
):
    """删除图片任务"""
    success = image_task.delete_task(db=db, task_id=task_id, user_id=current_user.id)
    if not success:
        raise HTTPException(status_code=404, detail="任务不存在")
    return {"code": 200, "msg": "删除成功"}

@router.post("/upload-batch", response_model=BatchImageUploadResponse)
async def batch_upload_images(
    *,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    background_tasks: BackgroundTasks,
    files: List[UploadFile] = File(...),
    task_id: Optional[int] = Form(None),
    task_name: Optional[str] = Form(None),
    description: Optional[str] = Form(None)
):
    """批量上传图片文件到任务"""
    
    # 验证输入
    if not files:
        raise HTTPException(status_code=400, detail="图片文件列表不能为空")
    
    if len(files) > 100:
        raise HTTPException(status_code=400, detail="最多支持100张图片")
    
    # 验证文件类型
    allowed_types = {'image/jpeg', 'image/png', 'image/gif', 'image/webp'}
    for file in files:
        if file.content_type not in allowed_types:
            raise HTTPException(status_code=400, detail=f"不支持的文件类型: {file.content_type}")
    
    # 处理任务
    if task_id:
        # 使用现有任务
        task = image_task.get_task(db=db, task_id=task_id, user_id=current_user.id)
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在")
    else:
        # 创建新任务
        if not task_name:
            raise HTTPException(status_code=400, detail="创建新任务时必须提供任务名称")
        
        task_create = ImageTaskCreate(
            task_name=task_name,
            description=description
        )
        task = image_task.create_task(db=db, task_data=task_create, user_id=current_user.id)
    
    # 启动后台任务处理图片上传
    background_tasks.add_task(
        process_batch_file_upload,
        task.id,
        files,
        db
    )
    
    return BatchImageUploadResponse(
        code=200,
        msg="批量上传已启动",
        data={
            "task_id": task.id,
            "task_name": task.task_name,
            "image_count": len(files)
        }
    )

async def process_batch_file_upload(task_id: int, files: List[UploadFile], db: Session):
    """后台处理批量文件上传"""
    cos_service = TencentCOSService()
    processor = ImageProcessor()
    
    successful_images = []  # 只保存成功的图片
    
    for i, file in enumerate(files):
        try:
            # 读取文件内容
            contents = await file.read()
            
            # 获取文件扩展名
            file_extension = file.filename.split('.')[-1] if '.' in file.filename else 'jpg'
            
            # 上传到COS
            upload_result = cos_service.upload_image(
                image_data=contents,
                file_extension=file_extension,
                folder="image_tasks"
            )
            
            # 只有上传成功才添加到数据库
            image_data = {
                "image_url": upload_result.get('url'),  # 使用COS URL
                "original_filename": file.filename,
                "file_size": len(contents),
                "file_type": file.content_type,
                "upload_status": "success",
                "sort_order": len(successful_images)
            }
            
            db_image = image_task.add_image_to_task(db=db, task_id=task_id, image_data=image_data)
            successful_images.append(db_image)
            
        except Exception as e:
            # 上传失败的图片不保存到数据库，只记录日志
            print(f"图片上传失败，跳过保存: {file.filename}, 错误: {str(e)}")
            continue
    
    # 更新任务的成功图片数量
    db_task = db.query(ImageTask).filter(ImageTask.id == task_id).first()
    if db_task:
        db_task.image_count = len(successful_images)
        db.commit()